#!/usr/bin/env bash
# 评分统计脚本

set -o pipefail

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# 获取脚本所在目录的父目录（项目根目录）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

SCORE_DIR="${1:-$PROJECT_ROOT/score}"
SCORE_FILE="${SCORE_DIR}/all_reviews.txt"

echo -e "${CYAN}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║                   📊 PR 评审统计分析                      ║${NC}"
echo -e "${CYAN}╚══════════════════════════════════════════════════════════╝${NC}"
echo

# 检查是否有记录文件
if [[ ! -f "$SCORE_FILE" ]]; then
  echo -e "${RED}❌ 没有找到评分记录文件：${SCORE_FILE}${NC}"
  exit 1
fi

# 统计基本信息
echo -e "${BLUE}📈 基本统计${NC}"
TOTAL_REVIEWS=$(grep "^#[0-9]" "$SCORE_FILE" 2>/dev/null | wc -l | tr -d ' ')
echo -e "   评审总数：${GREEN}${TOTAL_REVIEWS}${NC}"

if [[ "$TOTAL_REVIEWS" -eq 0 ]]; then
  echo -e "${YELLOW}暂无评审记录${NC}"
  exit 0
fi

# 计算平均分
AVG_SCORE=$(grep "^#[0-9]" "$SCORE_FILE" | awk -F'|' '{sum+=$5; count++} END {if(count>0) printf "%.1f", sum/count; else print "0"}')
echo -e "   平均得分：${GREEN}${AVG_SCORE}分${NC}"

# 最高分和最低分
MAX_SCORE=$(grep "^#[0-9]" "$SCORE_FILE" | awk -F'|' '{print $5}' | sort -rn | head -1)
MIN_SCORE=$(grep "^#[0-9]" "$SCORE_FILE" | awk -F'|' '{print $5}' | sort -n | head -1)
echo -e "   最高得分：${GREEN}${MAX_SCORE}分${NC}"
echo -e "   最低得分：${YELLOW}${MIN_SCORE}分${NC}"
echo

# 风险等级分布
echo -e "${BLUE}🎯 风险等级分布${NC}"
LOW_RISK=$(grep "低风险" "$SCORE_FILE" 2>/dev/null | wc -l | tr -d ' ')
MED_RISK=$(grep "中等风险" "$SCORE_FILE" 2>/dev/null | wc -l | tr -d ' ')
HIGH_RISK=$(grep "高风险" "$SCORE_FILE" 2>/dev/null | wc -l | tr -d ' ')

echo -e "   🟢 低风险：  ${GREEN}${LOW_RISK}${NC} 个"
echo -e "   🟡 中等风险：${YELLOW}${MED_RISK}${NC} 个"
echo -e "   🔴 高风险：  ${RED}${HIGH_RISK}${NC} 个"
echo

# 合并状态分布
echo -e "${BLUE}🔀 合并状态分布${NC}"
MERGED=$(grep "已合并" "$SCORE_FILE" 2>/dev/null | wc -l | tr -d ' ')
NOT_MERGED=$(grep "未合并" "$SCORE_FILE" 2>/dev/null | wc -l | tr -d ' ')
PENDING=$(grep "待处理" "$SCORE_FILE" 2>/dev/null | wc -l | tr -d ' ')
# 如果没有找到，设置为0
MERGED=${MERGED:-0}
NOT_MERGED=${NOT_MERGED:-0}
PENDING=${PENDING:-0}

echo -e "   ✅ 已合并：${GREEN}${MERGED}${NC} 个"
echo -e "   ❌ 未合并：${RED}${NOT_MERGED}${NC} 个"
echo -e "   ⏳ 待处理：${YELLOW}${PENDING}${NC} 个"
echo

# 最近5条记录
echo -e "${BLUE}📅 最近5条评审记录${NC}"
echo -e "${CYAN}PR编号 | 标题                 | 风险等级 | 评分 | 合并状态${NC}"
echo -e "${CYAN}-------|---------------------|----------|------|----------${NC}"

# 获取最近的5条记录（文件中的记录是按时间顺序的）
RECENT_RECORDS=$(grep "^#[0-9]" "$SCORE_FILE" 2>/dev/null | tail -5)

if [[ -n "$RECENT_RECORDS" ]]; then
  echo "$RECENT_RECORDS" | while IFS='|' read -r pr title author risk score status time; do
    # 清理空格
    pr=$(echo "$pr" | sed 's/^#//')
    title=$(echo "$title" | xargs)
    risk=$(echo "$risk" | xargs)
    score=$(echo "$score" | xargs)
    status=$(echo "$status" | xargs)
    
    # 截断标题长度
    if [[ ${#title} -gt 20 ]]; then
      title_short="${title:0:17}..."
    else
      title_short="$title"
    fi
    
    # 根据风险等级设置颜色
    case "$risk" in
      "低风险")
        risk_color="${GREEN}"
        ;;
      "中等风险")
        risk_color="${YELLOW}"
        ;;
      "高风险")
        risk_color="${RED}"
        ;;
      *)
        risk_color="${NC}"
        ;;
    esac
    
    # 根据合并状态设置颜色
    case "$status" in
      "已合并")
        status_color="${GREEN}"
        ;;
      "未合并")
        status_color="${RED}"
        ;;
      "待处理")
        status_color="${YELLOW}"
        ;;
      *)
        status_color="${NC}"
        ;;
    esac
    
    printf "%-7s | %-20s | ${risk_color}%-8s${NC} | %-4s | ${status_color}%-8s${NC}\n" \
      "$pr" "$title_short" "$risk" "$score" "$status"
  done
else
  echo -e "${YELLOW}暂无记录${NC}"
fi

echo

# 按用户统计
echo -e "${BLUE}👥 按用户统计${NC}"
echo -e "${CYAN}用户         | PR数量 | 平均分 | 合并率${NC}"
echo -e "${CYAN}-------------|--------|--------|--------${NC}"

# 收集所有用户数据
declare -A user_count
declare -A user_scores
declare -A user_merged

while IFS='|' read -r pr title author risk score status time repo; do
  if [[ "$pr" =~ ^#[0-9] ]]; then
    author=$(echo "$author" | xargs)
    
    # 跳过"待解析"或空用户
    if [[ "$author" == "待解析" ]] || [[ -z "$author" ]]; then
      continue
    fi
    
    # 确保score是数字
    if [[ "$score" =~ ^[0-9]+$ ]]; then
      # 统计用户PR数量
      ((user_count[$author]++))
      
      # 累加分数
      user_scores[$author]=$((${user_scores[$author]:-0} + score))
      
      # 统计合并数
      status=$(echo "$status" | xargs)
      if [[ "$status" == "已合并" ]]; then
        ((user_merged[$author]++))
      fi
    fi
  fi
done < "$SCORE_FILE"

# 输出用户统计（检查是否有用户数据）
if [[ ${#user_count[@]} -gt 0 ]]; then
  for user in "${!user_count[@]}"; do
    count=${user_count[$user]}
    total_score=${user_scores[$user]}
    merged=${user_merged[$user]:-0}
    
    # 计算平均分和合并率
    if command -v bc &> /dev/null; then
      avg_score=$(echo "scale=1; $total_score / $count" | bc)
      merge_rate=$(echo "scale=1; $merged * 100 / $count" | bc)
    else
      avg_score=$((total_score / count))
      merge_rate=$((merged * 100 / count))
    fi
    
    printf "%-12s | %-6d | %-6s | %s%%\n" \
      "$user" "$count" "$avg_score" "$merge_rate"
  done | sort -t'|' -k2 -rn | head -5
else
  echo -e "${YELLOW}暂无用户统计数据${NC}"
fi

echo
echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# 提示信息
echo -e "\n${YELLOW}💡 提示:${NC}"
echo -e "  • 使用 ${GREEN}./scripts/score_stats.sh${NC} 查看所有统计"
echo -e "  • 评分记录保存在 ${BLUE}score/all_reviews.txt${NC} 文件中"
echo -e "  • 所有PR的评分记录都集中在一个文件中管理"